const express = require('express'),
    router = express.Router()
const async = require('async')
const request = require('request')
const moment = require('moment');


const appID = "wx15bd640984145f64";
const appsecret = "d2773a4639dc52e04fe03cd2c38cf07c";


module.exports.getAccessToken = function getAccessToken(callback) {
    redisClient.get('miniapp_token', function(err, data) {
            if (data == null || data == 'undefined') {
                var wxurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appsecret
                request({
                    url: wxurl,
                    method: "GET",
                    timeout: 10000,
                    followRedirect: true,
                    maxRedirects: 10
                }, function(error, response, body) {
                    redisClient.set('miniapp_token', JSON.parse(body).access_token, function(err, success) {
                        redisClient.expire('miniapp_token', parseInt(JSON.parse(body).expires_in), function(err, ress) {
                            callback(JSON.parse(body).access_token)
                        })
                    })
                })
            } else {
                // console.log('had', data)
                callback(data)
            }

        })
}


